import 'package:flutter/material.dart';
import '../dao/todo_dao.dart';
import '../models/todo.dart';

class TodoListScreen extends StatefulWidget {
  const TodoListScreen({Key? key}) : super(key: key);

  @override
  _TodoListScreenState createState() => _TodoListScreenState();
}

class _TodoListScreenState extends State<StatefulWidget> {
  final TodoDao _todoDao = TodoDao();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  List<Todo> _todos = [];
  bool _showCompleted = false;

  @override
  void initState() {
    super.initState();
    _loadTodos();
  }

  Future<void> _loadTodos() async {
    List<Todo> todos;
    if (_showCompleted) {
      todos = await _todoDao.getCompletedTodos();
      print('Loaded completed todos: ${todos.length}');
    } else {
      todos = await _todoDao.getPendingTodos();
      print('Loaded pending todos: ${todos.length}');
    }
    setState(() {
      _todos = todos;
    });
  }

  Future<void> _addTodo() async {
    if (_titleController.text.isEmpty) return;

    final newTodo = Todo(
      title: _titleController.text,
      description: _descriptionController.text,
      createdAt: DateTime.now(),
    );
    await _todoDao.insertTodo(newTodo);
    _titleController.clear();
    _descriptionController.clear();
    _loadTodos();
  }

  Future<void> _toggleTodoCompletion(Todo todo) async {
    final updateTodo = Todo(
        id: todo.id,
        title: todo.title,
        description: todo.description,
        isCompleted: !todo.isCompleted,
        createdAt: todo.createdAt);
    await _todoDao.updateTodo(updateTodo);
    _loadTodos();
  }

  Future<void> _deleteTodo(int id) async {
    await _todoDao.deleteTodo(id);
    _loadTodos();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      appBar: AppBar(

        title: const Text('Todo App'),
        actions: [
          IconButton(
            onPressed: () {
              setState(() {
                _showCompleted = !_showCompleted;
                _loadTodos();
              });
            },
            icon: Icon(_showCompleted
                ? Icons.check_circle
                : Icons.check_circle_outline),
          )
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                TextField(
                  controller: _titleController,
                  decoration: const InputDecoration(
                    labelText: 'Title',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _descriptionController,
                  decoration: const InputDecoration(
                      labelText: 'Description(optional)',
                      border: OutlineInputBorder()),
                ),
                const SizedBox(height: 10),
                ElevatedButton(
                    onPressed: _addTodo, child: const Text('Add Todo'))
              ],
            ),
          ),
          Expanded(
              child: ListView.builder(
                  itemCount: _todos.length,
                  itemBuilder: (context, index) {
                    final todo = _todos[index];
                    return Dismissible(
                        key: Key(todo.id.toString()),
                        background: Container(color: Colors.red),
                        onDismissed: (direction) => _deleteTodo(todo.id!),
                        child: ListTile(
                          title: Text(todo.title),
                          subtitle: todo.description.isNotEmpty
                              ? Text(todo.description)
                              : null,
                          trailing: Checkbox(
                            value: todo.isCompleted,
                            onChanged: (value) => _toggleTodoCompletion(todo),
                          ),
                        ));
                  }))
        ],
      ),
    );
  }
}
